package com.znow.admin.system.security.authentication;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 验证码登录
 *
 * @author nemo
 * @date 2024/01/08
 */
public class SmsCodeAuthFilter extends AbstractAuthenticationProcessingFilter {

    public static final String MOBILE = "mobile";
    public static final String CODE = "code";

    private boolean postOnly = true;

    public SmsCodeAuthFilter() {
        super(new AntPathRequestMatcher("/sms/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }

        String mobile = obtainMobile(request);
        String code = obtainMobileCode(request);

        SmsCodeAuthToken authRequest = new SmsCodeAuthToken(mobile, code);
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }


    /**
     * 获取手机号
     *
     * @param request
     * @return
     */
    protected String obtainMobile(HttpServletRequest request) {
        return request.getParameter(MOBILE);
    }

    /**
     * 获取手机号
     *
     * @param request
     * @return
     */
    protected String obtainMobileCode(HttpServletRequest request) {
        return request.getParameter(CODE);
    }

    protected void setDetails(HttpServletRequest request,
                              SmsCodeAuthToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }

}